//
//  YHRouter+Map.m
//  YHRouter
//
//  Created by 98du on 2021/12/1.
//

#import "YHRouter+Map.h"
#import "YHConstant+Null.h"
#import "UIViewController+YHRouter.h"

@import Bifrost;

@implementation YHRouter (Map)

#pragma mark - Bifrost

/// 在需要被跳转的控制器中 +load 中设置
/// @param key 最好 module+classname
/// @param handler 参数信息
+ (void)yh_bindKey:(nonnull NSString *)key
           vcClass:(Class)vcClass
         toHandler:(nonnull _Nullable id (^)(NSDictionary * _Nullable))handler{
    [Bifrost bindURL:key toHandler:handler];
}

+ (nullable UIViewController *)yh_handleKey:(nonnull NSString *)key{
    return [self yh_handleKey:key params:nil callBack:nil];
}

+ (nullable UIViewController *)yh_handleKey:(nonnull NSString *)key
                                     params:(nullable NSDictionary*)params{
    return [self yh_handleKey:key params:params callBack:nil];
}

+ (nullable UIViewController *)yh_handleKey:(nonnull NSString *)key
                                     params:(nullable NSDictionary*)params
                                   callBack:(nullable YHRouterCallBlock)callBack{
    UIViewController * vc = [Bifrost handleURL:key complexParams:params completion:nil];
    vc.yh_callback = callBack;
    return vc;
}

#pragma mark -
+ (void)yh_bindKey:(nonnull NSString *)key vcClass:(Class)vcClass{
    [YHRouter yh_bindKeys:@[key] vcClass:vcClass];
}
/// 数组中的元素可以是字符串或者整形：@[@"home",@"main",@(1),@"1"]
+ (void)yh_bindKeys:(nonnull NSArray *)keys vcClass:(Class)vcClass{
    NSArray * oldKeys = [YHRouter yh_bindKeysAtVCClass:vcClass];
    NSMutableArray * newKeys = [NSMutableArray new];
    if(oldKeys){
        [newKeys addObjectsFromArray:oldKeys];
    }
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(![newKeys containsObject:obj]){
            [newKeys addObject:obj];
        }
    }];
    [YHRouter sharedManager].mapKeys[NSStringFromClass(vcClass)] = newKeys;
}

+ (void)yh_removeBindKeysByVCClass:(Class)vcClass{
    [[YHRouter sharedManager].mapKeys removeObjectForKey:NSStringFromClass(vcClass)];
}
+ (NSArray *)yh_bindKeysAtVCClass:(Class)vcClass{
    NSArray * keys = [[YHRouter sharedManager].mapKeys objectForKey:NSStringFromClass(vcClass)];
    return keys?:@[];
}


/// 通过Key获取map对应的控制器
+ (UIViewController *)yh_controllerKey:(NSString *)key{
    if(IsNull(key)){
        return nil;
    }
    // 判断handle中是否有绑定关系
    if([Bifrost canHandleURL:key]){
        return [YHRouter yh_handleKey:key];
    }
    
    NSString * sbName = nil;
    NSString * sbIdentifier = nil;
    Class vcClass = NSClassFromString(key);
    NSString * classname = key;
    if(!vcClass){
        classname = [YHRouter __yh_queryClassNameKey:key];
        sbIdentifier = classname;
        if([classname containsString:@"."]){
            sbName = [classname componentsSeparatedByString:@"."].firstObject;
            sbIdentifier = [classname componentsSeparatedByString:@"."].lastObject;
        }
        vcClass = NSClassFromString(sbIdentifier);
    }
    
    if(!vcClass){
        if([YHRouter sharedManager].errorHandler){
            [YHRouter sharedManager].errorHandler(YHRouterErrorCodeClassNotFound, [NSString stringWithFormat:@"没有找到控制器：%@ 的定义",key]);
        }
        return nil;
    }
  
    UIViewController *targetController;
    if(sbName){
        targetController = [[UIStoryboard storyboardWithName:sbName bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:sbIdentifier];
        if(!targetController){
            if([YHRouter sharedManager].errorHandler){
                [YHRouter sharedManager].errorHandler(YHRouterErrorCodeClassNotFound, [NSString stringWithFormat:@"在 storyboard %@ 中没有找到该控制器 %@ ",sbName,sbIdentifier]);
            }
            return nil;
        }
    }else{
        targetController = [vcClass new];
    }
    if(![targetController isKindOfClass:[UIViewController class]]){
        if([YHRouter sharedManager].errorHandler){
            [YHRouter sharedManager].errorHandler(YHRouterErrorCodeClassNotFound, [NSString stringWithFormat:@"不是ViewController类型： %@ ",key]);
        }
        return nil;
    }
    return targetController;
}

/// 通过key查找对应的class
+ (NSString *)__yh_queryClassNameKey:(NSString *)mapKey{
    __block NSString * reslutMapper = nil;
    [[YHRouter sharedManager].mapKeys enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull vcClassname, NSArray * _Nonnull obj, BOOL * _Nonnull stop) {
        for (NSString * oneKey in obj) {
            if([oneKey isKindOfClass:[NSString class]]){
                if([oneKey isEqualToString:mapKey]){
                    reslutMapper = vcClassname;
                    return;
                }
            }else if ([oneKey isKindOfClass:[NSNumber class]]){
                NSNumber * oneKeyNum = (NSNumber *)oneKey;
                if([oneKeyNum.stringValue isEqualToString:mapKey]){
                    reslutMapper = vcClassname;
                    return;
                }
            }
        }
    }];
    return reslutMapper;
}


@end
